/*
 * @lc app=leetcode.cn id=145 lang=cpp
 *
 * [145] 二叉树的后序遍历
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        if (root == nullptr)
            return {};


        std::vector<int> result;
        std::stack<TreeNode*> nodes;
        nodes.push(root);

        while (!nodes.empty()) {
            auto node = nodes.top();
            if (node != nullptr) {
                nodes.pop();

                //左 右 根, 入栈时逆序
                nodes.push(node);
                nodes.push(nullptr);    //标记
                
                if (node->right != nullptr) nodes.push(node->right);
                if (node->left != nullptr) nodes.push(node->left);

            }

            else {  //进入标记节点
                nodes.pop();

                node = nodes.top();
                nodes.pop();

                result.push_back(node->val);
            }
        }

        return result;
    }
};
// @lc code=end

